package com.jijuxie.house.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jijuxie.house.domain.HouseImage;
import com.jijuxie.house.mapper.HouseImageMapper;
import com.jijuxie.house.service.IHouseImageService;
import com.jijuxie.framework.config.UploadConfig;
import com.jijuxie.common.exception.ServiceException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;
import java.time.LocalDateTime;

@Service
public class HouseImageServiceImpl extends ServiceImpl<HouseImageMapper, HouseImage> implements IHouseImageService {

    private static final Logger log = LoggerFactory.getLogger(HouseImageServiceImpl.class);

    @Autowired
    private UploadConfig uploadConfig;

    @Autowired
    private HouseImageMapper imageMapper;

    @Override
    public HouseImage uploadImage(MultipartFile file, Long houseId, String imageType) throws IOException {
        // 1. 校验文件
        if (file.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }

        // 2. 校验文件类型
        String extension = getExtension(file.getOriginalFilename());
        if (!isAllowedExtension(extension)) {
            throw new ServiceException("只能上传jpg、jpeg、png、gif格式的图片");
        }

        // 3. 检查封面图和户型图是否已存在
        if ("1".equals(imageType) || "3".equals(imageType)) {
            HouseImage existingImage = imageMapper.selectOne(
                    new LambdaQueryWrapper<HouseImage>()
                            .eq(HouseImage::getHouseId, houseId)
                            .eq(HouseImage::getImageType, imageType)
            );
            if (existingImage != null) {
                // 删除旧图片
                deleteImage(existingImage.getImageId());
            }
        }

        // 4. 生成文件名
        String fileName = UUID.randomUUID().toString() + "." + extension;

        // 5. 确保上传目录存在
        File uploadDir = new File(uploadConfig.getPath());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 6. 保存文件
        File dest = new File(uploadDir, fileName);
        file.transferTo(dest);

        // 7. 保存图片信息
        HouseImage image = new HouseImage();
        image.setHouseId(houseId);
        image.setImageType(imageType);
        image.setImageUrl(uploadConfig.getUrl() + fileName);
        image.setSort(getMaxSort(houseId) + 1);
        image.setUploadTime(LocalDateTime.now());
        save(image);

        return image;
    }

    private boolean isAllowedExtension(String extension) {
        String[] allowed = {"jpg", "jpeg", "png", "gif"};
        return Arrays.asList(allowed).contains(extension.toLowerCase());
    }

    private String getExtension(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    @Override
    public void deleteImage(Long imageId) {
        log.info("开始删除图片：imageId={}", imageId);

        // 1. 查询图片信息
        HouseImage image = imageMapper.selectById(imageId);
        if (image == null) {
            throw new ServiceException("图片不存在");
        }

        try {
            // 2. 删除物理文件
            String fileName = image.getImageUrl().substring(image.getImageUrl().lastIndexOf("/") + 1);
            File file = new File(uploadConfig.getPath(), fileName);
            if (file.exists()) {
                boolean deleted = FileUtils.deleteQuietly(file);
                if (!deleted) {
                    log.error("物理文件删除失败：{}", file.getAbsolutePath());
                    throw new ServiceException("图片文件删除失败");
                }
                log.info("物理文件删除成功：{}", file.getAbsolutePath());
            } else {
                log.warn("物理文件不存在：{}", file.getAbsolutePath());
            }

            // 3. 删除数据库记录
            int rows = imageMapper.deleteById(imageId);
            if (rows == 0) {
                throw new ServiceException("数据库记录删除失败");
            }
            log.info("数据库记录删除成功：imageId={}", imageId);

            // 4. 重新排序其他图片
            imageMapper.reorderImages(image.getHouseId(), image.getSort());
            log.info("重新排序完成：houseId={}", image.getHouseId());

        } catch (Exception e) {
            log.error("删除图片失败：", e);
            throw new ServiceException("删除图片失败：" + e.getMessage());
        }
    }

    @Override
    public void updateSort(Long imageId, Integer sort) {
        log.info("开始更新图片排序：imageId={}, sort={}", imageId, sort);

        HouseImage image = imageMapper.selectById(imageId);
        if (image == null) {
            throw new ServiceException("图片不存在");
        }

        image.setSort(sort);
        int rows = imageMapper.updateById(image);
        log.info("更新图片排序结果：rows={}", rows);

        if (rows == 0) {
            throw new ServiceException("更新排序失败");
        }
    }

    private Integer getMaxSort(Long houseId) {
        return imageMapper.selectMaxSort(houseId);
    }
}
